package com.vst.orm.dao.hibernate;

import java.io.Serializable;
import java.util.List;

import com.vst.orm.dao.DAOUtil;
import com.vst.orm.search.ExampleOptions;
import com.vst.orm.search.Filter;
import com.vst.orm.search.ISearch;
import com.vst.orm.search.Search;
import com.vst.orm.search.SearchResult;

public class GenericDAOImpl<T, ID extends Serializable> extends HibernateBaseDAO implements GenericDAO<T, ID> {
	protected Class<T> persistentClass = (Class) DAOUtil.getTypeArguments(GenericDAOImpl.class, getClass()).get(0);

	public int count(ISearch search) {
		if (search == null) {
			search = new Search();
		}
		return _count(this.persistentClass, search);
	}

	public T find(Serializable id) {
		return (T) _get(this.persistentClass, id);
	}

	public T[] find(Serializable... ids) {
		return _get(this.persistentClass, ids);
	}

	public List<T> findAll() {
		return _all(this.persistentClass);
	}

	public void flush() {
		_flush();
	}

	public T getReference(Serializable id) {
		return (T) _load(this.persistentClass, id);
	}

	public T[] getReferences(Serializable... ids) {
		return _load(this.persistentClass, ids);
	}

	public boolean isAttached(T entity) {
		return _sessionContains(entity);
	}

	public void refresh(T... entities) {
		_refresh(entities);
	}

	public boolean remove(T entity) {
		return _deleteEntity(entity);
	}

	public void remove(T... entities) {
		_deleteEntities(entities);
	}

	public boolean removeById(Serializable id) {
		return _deleteById(this.persistentClass, id);
	}

	public void removeByIds(Serializable... ids) {
		_deleteById(this.persistentClass, ids);
	}

	public boolean save(T entity) {
		return _saveOrUpdateIsNew(entity);
	}

	public boolean[] save(T... entities) {
		return _saveOrUpdateIsNew(entities);
	}

	public <RT> List<RT> search(ISearch search) {
		if (search == null) {
			return (List<RT>) findAll();
		}
		return _search(this.persistentClass, search);
	}

	public <RT> SearchResult<RT> searchAndCount(ISearch search) {
		if (search == null) {
			SearchResult<RT> result = new SearchResult();
			result.setResult((List<RT>) findAll());
			result.setTotalCount(result.getResult().size());
			return result;
		}
		return _searchAndCount(this.persistentClass, search);
	}

	public <RT> RT searchUnique(ISearch search) {
		return (RT) _searchUnique(this.persistentClass, search);
	}

	public Filter getFilterFromExample(T example) {
		return _getFilterFromExample(example);
	}

	public Filter getFilterFromExample(T example, ExampleOptions options) {
		return _getFilterFromExample(example, options);
	}
}
